package com.atguigu.flink.charkoer08;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;

public class FlinkWindows03 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<String> main = env.socketTextStream("hadoop162", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] line = value.split(" ");
                        for (String word : line) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //得到乱序时间
                                .<Tuple2<String, Integer>>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                //告诉他怎么拿到事件的时间戳
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Integer>>() {
                                    //返回事件时间必须是一个毫秒值
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Integer> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(x -> x.f0)
                // .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                //.window(SlidingProcessingTimeWindows.of(Time.seconds(5),Time.seconds(2)))
                .window(ProcessingTimeSessionWindows.withGap(Time.seconds(3)))
                //允许迟到的时间
                // 当到了窗口的关闭时间, 先对窗口内的元素进行计算,但是暂时不关闭窗口
                // 在允许的时间范围内, 如果还有属于这个窗口的数据,则继续进入窗口计算.
//                .allowedLateness(Time.seconds(3))
                .sideOutputLateData(new OutputTag<Tuple2<String, Integer>>("late") {
                })
                .process(new ProcessWindowFunction<Tuple2<String, Integer>, String, String, TimeWindow>() {

                    @Override
                    public void process(String s,
                                        Context context,
                                        Iterable<Tuple2<String, Integer>> elements,
                                        Collector<String> out) throws Exception {
                        HashMap<String, Integer> idToSum = new HashMap<>();

                        Date stt = new Date(context.window().getStart());
                        Date edt = new Date(context.window().getEnd());
                        for (Tuple2<String, Integer> element : elements) {
                            Integer sum = idToSum.getOrDefault(s, 0);
                            sum += element.f1;
                            idToSum.put(s, sum);
                        }

                        out.collect(idToSum.toString() + " " + stt + " " + edt);
                    }
                });
        main.print("s1");
        main.getSideOutput(new OutputTag<Tuple2<String, Integer>>("late") {
        }).print("last");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
